package com.baidu.travel.timedtask.service.impl;

import com.alibaba.fastjson.JSON;
import com.baidu.travel.domain.Comment;
import com.baidu.travel.domain.CommentVO;
import com.baidu.travel.timedtask.dao.CommentTimingDao;
import com.baidu.travel.timedtask.service.CommentTimingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentTimingServiceImpl implements CommentTimingService {

    @Autowired
    private CommentTimingDao commentTimingDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Boolean timedCacheComments() {
        //将评论表中的路线rid拿到
        Integer[] commentRid = commentTimingDao.getCommentRid();
        //将每条路线最新的10条评论返回
        List<Comment> comments = commentTimingDao.getComments();
        List<CommentVO> commentVo = new ArrayList<>();
        for (Comment comment : comments) {
            try {
                CommentVO clone = comment.clone(CommentVO.class);
                clone.setText(comment.getContent());
                commentVo.add(clone);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            for (int i=0;i<commentRid.length;i++){
                List<CommentVO> list = new ArrayList<>();
                for (int j=0;j<comments.size();j++){
                    if (commentRid[i].equals(comments.get(j).getRid())){
                        list.add(commentVo.get(j));
                    }
                }
                //将list转为json字符串  取的时候再转为list对象
                //因为直接将lsit存到redis中格式为[{"href":null,"text":"傻酱  大**"},{"href":null,"text":"**"},{"href":null,"text":"343242"},{"href":null,"text":"453"},{"href":null,"text":"我爱这里"}]
                //前端只能处理这样的格式[CommentVO(href=null, text=我爱这里), CommentVO(href=null, text=343242), CommentVO(href=null, text=**), CommentVO(href=null, text=傻酱  大**), CommentVO(href=null, text=453)]
                redisTemplate.opsForValue().set("USER:COMMENT:ROUTE:"+commentRid[i], JSON.toJSONString(list));
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
